package org.farm.controller;

import org.farm.Enum.ResultCodeEnum;
import org.farm.dto.LoginDTO;
import org.farm.dto.RegisterDTO;
import org.farm.pojo.ResultVo;
import org.farm.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private SysUserService userService;

    @PostMapping("/login")
    public ResponseEntity<ResultVo<Map<String, Object>>> login(@RequestBody LoginDTO loginDTO) {
        try {
            ResultVo<Map<String, Object>> result = userService.login(loginDTO);
            if (result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
        } catch (Exception e) {
            ResultVo<Map<String, Object>> errorResult = ResultVo.fails(ResultCodeEnum.SERVICE_ERROR, "服务异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResult);
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<String> logout(@RequestHeader("Authorization") String token) {
        userService.logout(token.replace("Bearer ", ""));
        return ResponseEntity.ok("登出成功");
    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody RegisterDTO registerDTO) {
        try {
            userService.register(registerDTO);
            return ResponseEntity.ok("注册成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("注册失败: " + e.getMessage());
        }
    }
}